package com.taocore.top.title.action;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.taobao.api.ApiException;
import com.taobao.api.response.ItemUpdateResponse;
import com.taocore.top.title.db.DBUtils;
import com.taocore.top.title.db.Dao;
import com.taocore.top.title.service.TaobaoService;

@Results({
	@Result(name="success", type="httpheader"),
	@Result(name="error", type="httpheader", params={"headers.error", "true", "headers.msg", "${msg}"})
})
public class UpdateTitleAction extends ActionBase{
	
	static Logger _log = Logger.getLogger(UpdateTitleAction.class.getName());
	
	private long numIid;
	private String title;
	private String msg;
	
	public String execute()
	{
		_log.info("title: " + title);
		TaobaoService service = new TaobaoService();
		String session = getSessionId();
		try {
			ItemUpdateResponse rsp = service.updateTitle(numIid, title, session);
			if (rsp.isSuccess())
			{
				addTitleHistoryItem(title, numIid);
				return SUCCESS;
			}
			else
			{
				_log.warning(TaobaoService.getError(rsp));
				String subMsg = rsp.getSubMsg();
				if (subMsg != null)
				{
					msg = new String(subMsg.getBytes("UTF-8"), "ISO-8859-1");
				}
			}
		} catch (ApiException e) {
			_log.log(Level.SEVERE, "", e);
		} catch (UnsupportedEncodingException e) {
			_log.log(Level.SEVERE, "", e);
		}
		return ERROR;
	}
	
	private void addTitleHistoryItem(String title, long numIid)
	{
		Connection conn = null;
		try
		{
			conn = DBUtils.getConnection();
			Dao.INSTANCE.addTitleHistoryItem(title, numIid, conn);
		}
		catch (Exception e) {
			_log.log(Level.SEVERE, "", e);
		}
		finally
		{
			DBUtils.close(conn, null, null);
		}
	}

	public void setNumIid(long numIid) {
		this.numIid = numIid;
	}

	public long getNumIid() {
		return numIid;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getMsg() {
		return msg;
	}

}
